//
//  MXCollocaTionVC.m
//  MXの衣柜
//
//  Created by 马霄 on 15/8/4.
//  Copyright (c) 2015年 霄 马. All rights reserved.
//  搭配首页

#import "MXCollocaTionVC.h"
//--------------------- 添加三方 ----------------------
#import "AFNetworkHandler.h"
//--------------------- 添加Model类 ----------------------
#import "MXStyleModel.h"
#import "MXCollocationContentModel.h"
//测试 TableView中自定义Cell加载CollectionView
//--------------------- 添加自定义Cell ----------------------
#import "MXOccoasionTopViewTableViewCell.h"
// 添加搭配的主页的内容的CollectionViewCell
#import "MXCollocationContentCollectionViewCell.h"

// 添加搭配的商品的详情页面
#import "MXCollocaCarefulChosenVC.h"

#import "MXCollocaStyleAndCationVC.h"

#import "MJRefresh.h"
#import "MBProgressHUD.h"


@interface MXCollocaTionVC ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate>
//========================== 创建属性 ===================================
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UITableView *tableView;

//@property (nonatomic, retain) MXCollocationTopView *topView;
//========================== 风格全局数组 ===================================
@property (nonatomic, retain) NSMutableArray *styleArray;

//========================== 场合全局数组 ===================================
@property (nonatomic, retain) NSMutableArray *occocasionArray;

//========================== 精选全局数组 ===================================
@property (nonatomic, retain) NSMutableArray *contentArray;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, retain) MXOccoasionTopViewTableViewCell *cell;

@property (nonatomic,retain) MBProgressHUD *HUD;

@property (nonatomic, retain) UIView *alterView;

@property (nonatomic, retain) NSTimer *timer;
@end

@implementation MXCollocaTionVC
- (void)dealloc
{
    [_timer release];
    [_HUD release];
    [_alterView release];
    [_contentArray release];
    [_cell release];
    [_tableView release];
    [_styleArray release];
    [_occocasionArray release];
    [_collectionView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Home_titleBackGround"] forBarMetrics:UIBarMetricsDefault];

    
    self.title = @"搭配";
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:26 / 255.0 green:62 / 255.0 blue:230 / 255.0 alpha:1];
    self.navigationController.navigationBar.alpha = 0.5;
    
//全局数组初始化
    self.styleArray = [NSMutableArray array];
    self.occocasionArray = [NSMutableArray array];
    self.contentArray = [NSMutableArray array];
    
    
    
#pragma mark - 先加载数据部分
    [self GetcontentData];
    
    
    [self creatTableView];
    
    [self GetTopData];
    
    self.pageNum = 2;
    
    // 添加刷新方法
    [self loadingCollectionView];
    
    [self refreshTableView];

    
    [self creatCollectionView];
    
    [self uiActivityindicatorviewStart];

    
}

-(void)uiActivityindicatorviewStart
{
    self.alterView =[[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.alterView.backgroundColor =[UIColor whiteColor];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.alterView animated:YES];
//    self.HUD.labelText = @"正在努力的给您加载";
    [self.HUD show:YES];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(uiActivityindicatorviewEnd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

    
    [self.view addSubview:self.alterView];
    
}
-(void)uiActivityindicatorviewEnd
{
    [self.alterView removeFromSuperview];
}

- (void)creatTableView
{
#warning TableView的Height 有点问题 需要调试 将滚动取消
    self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT -  HEIGHTPRO * (64 + 49)) style:(UITableViewStylePlain)] autorelease];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = YES;
    self.tableView.userInteractionEnabled = YES;
    
    
}

- (void)creatCollectionView
{
    
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    flowLayout.itemSize = CGSizeMake(WIDTHPRO * 170, HEIGHTPRO * 300);
    flowLayout.minimumLineSpacing = 10;
    flowLayout.sectionInset = UIEdgeInsetsMake(WIDTHPRO * 10 , HEIGHTPRO * 10 , 0, HEIGHTPRO * 10);
#pragma mark - 根据TopView手动更改
    flowLayout.headerReferenceSize = CGSizeMake(0, HEIGHT - HEIGHTPRO * (64 + 49));
    
    self.collectionView = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - HEIGHTPRO * 64) collectionViewLayout:flowLayout] autorelease];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.collectionView];
    
    
    [self.collectionView registerClass:[MXCollocationContentCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}


#pragma mark -- 下拉刷新
-(void)refreshTableView
{
    //    __block MXFindVC *findVC = self;
    [self.collectionView addHeaderWithCallback:^{
        //        [self GetFindData];
        [self.collectionView headerEndRefreshing];
    }];
    //添加下拉刷新头部控件
    
    //    [self.collectionView reloadData];
}

#pragma mark -- 上拉加载

-(void)loadingCollectionView
{
    
    //    __unsafe_unretained typeof(self) vc = self;
    [self.collectionView addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *contentPath = [NSString stringWithFormat:@"http://api.nanyibang.com/match-list?page=%ld", (long)self.pageNum];
            self.pageNum += 1;
            [AFNetworkHandler GETwithAFNByURL:contentPath completion:^(id result) {
                NSArray *dataArr = [result objectForKey:@"data"];
                for (NSDictionary *dict in dataArr) {
                    MXCollocationContentModel *model = [[[MXCollocationContentModel alloc ]initWithDic:dict] autorelease];
                    [self.contentArray addObject:model];
                }
            }];
            [self.collectionView reloadData];
            [self.collectionView footerEndRefreshing];
        });
    }];
}

/*************************解析HeaderView数据部分**************************/
- (void)GetTopData
{
    NSString *topPath = @"http://api.nanyibang.com/match-classify";
    
    [AFNetworkHandler GETwithAFNByURL:topPath completion:^(id result) {
        NSArray *dataArr = [result objectForKey:@"data"];
        for (NSDictionary *dict in dataArr) {
            MXStyleModel *model = [[[MXStyleModel alloc] initWithDic:dict] autorelease];
//========================== 风格 ===================================
            if ([model.name isEqualToString:@"风格"]) {
                for (NSDictionary *itemDict in model.items) {
                    MXStyleModel *styleModel = [[[MXStyleModel alloc] initWithDic:itemDict] autorelease];
                    [self.styleArray addObject:styleModel];
                    self.cell.tempArray = self.styleArray;
                }
            }
//========================== 场合 ===================================
            if ([model.name isEqualToString:@"主题"]) {
                for (NSDictionary *itemDict in model.items) {
                    MXStyleModel *occasionModel = [[[MXStyleModel alloc] initWithDic:itemDict] autorelease];
                    [self.occocasionArray addObject:occasionModel];
                    
                    
                }
            }
        }
        if (self.contentArray) {
            
            [self uiActivityindicatorviewEnd];
        }
        [self.tableView reloadData];
        
    }];
}
/************************* 解析精选数据部分 **************************/

- (void)GetcontentData
{
    NSString *contentPath = @"http://api.nanyibang.com/match-list?page=1";
    [AFNetworkHandler GETwithAFNByURL:contentPath completion:^(id result) {
        NSArray *dataArr = [result objectForKey:@"data"];
        for (NSDictionary *dict in dataArr) {
            MXCollocationContentModel *model = [[[MXCollocationContentModel alloc ]initWithDic:dict] autorelease];
            [self.contentArray addObject:model];
        }
        
        [self.collectionView reloadData];
        
        if (_occocasionArray) {
            
            [self uiActivityindicatorviewEnd];
        }

    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/************************* TableView Delegate **************************/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MXOccoasionTopViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[MXOccoasionTopViewTableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"reuse"];
    }

    cell.navi = self.navigationController;
    cell.tempArray = self.styleArray;
    cell.occoasionArray = self.occocasionArray;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.tableView.frame.size.height;
}



/************************* CollectionView Delegate **************************/
//Collection中的组别个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个组别中元件的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contentArray.count;
}
//重用机制

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXCollocationContentCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.cornerRadius = 8;
    cell.layer.masksToBounds = YES;
    MXCollocationContentModel *model = self.contentArray[indexPath.row];
    [cell GetInfo:model];
    return cell;
}
#pragma mark - 搭配主页CollectionView的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MXCollocaCarefulChosenVC *chosenVC = [[[MXCollocaCarefulChosenVC alloc] init] autorelease];
    chosenVC.careChosenID = [self.contentArray[indexPath.row] collocation_id];
    [self presentViewController:chosenVC animated:YES completion:^{
    }];
}

//设置HeaderView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *topView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    [topView addSubview:self.tableView];
    return topView;
}

#pragma mark - 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
